const Koa = require('koa');
const fs = require('fs');
const app = new Koa();
const staticServer = require('koa-static');

app.use(staticServer(__dirname, 'public'));

// 根据需求,读取相应的页面,并返回
function render(page) {
  return new Promise((resolve, reject) => {
    let pageUrl = `${__dirname}/${page}`;
    //生成二进制流
    fs.readFile(pageUrl, "utf-8", (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    })
  })
}

// 识别url,判断所请求的页面
async function route(url) {
  let page = '404.html';
  switch (url) {
    case '/':
      page = 'index.html';
      break;
    case '/index':
      page = 'index.html';
      break;
    case '/sin':
      page = 'sin.html';
      break;
    default:
      break;
  }
  let html = await render(page);
  return html;
}

app.use(async (ctx, next) => {
  let url = ctx.request.url;
  let html = await route(url);
  ctx.body = html;
});

app.listen(8888, () => {
  console.log('server is starting at port 8888');
});